/**
 * 获取元素路径
 * @param {*} element
 * @returns
 */
function getElementDomPath(element) {
  if (!element || !element.nodeType) {
    return null;
  }

  var path = [];
  while (element && element.nodeType === Node.ELEMENT_NODE) {
    var selector = element.nodeName.toLowerCase();
    if (element.id) {
      selector += `#${element.id}`;
    } else if (element.className) {
      selector += `.${element.className.split(" ").join(".")}`;
    }

    // 添加子节点的文本内容
    var childText = "";
    for (let child of element.childNodes) {
      if (child.nodeType === Node.TEXT_NODE) {
        childText += child.nodeValue.trim();
      }
    }
    if (childText) {
      selector += `: "${childText}"`;
    }

    path.unshift(selector); // 将选择器添加到路径的开头
    element = element.parentNode;
  }
  return path.join(" > ");
}

/**
 * 查找最近的带有埋点属性的元素
 * @param {*} element
 * @param {*} type
 * @returns
 */
export function findTrackNode(element, type) {
  while (element && element !== document.body) {
    if (element.hasAttribute(`data-track-${type}`)) {
      return element;
    }
    element = element.parentElement;
  }
  return null;
}

/**
 * 获取动态参数
 * @param {*} element
 * @returns
 */
export function getDynamicParams(element) {
  const params = {};

  // 获取 data-track-params 属性指定的参数
  const trackParams = element.getAttribute("data-track-params");
  if (trackParams) {
    trackParams.split(",").forEach((param) => {
      const [key, selector] = param.split(":").map((s) => s.trim());
      if (key && selector) {
        // 支持的选择器：id、class、属性
        if (["#", ".", "["].includes(selector[0])) {
          // 选择目标元素
          let targetElement = document.querySelector(selector);

          if (targetElement) {
            // 根据元素类型获取值
            params[key] = getElementValue(targetElement);
          }
        } else {
          // 非选择器直接赋值
          params[key] = selector;
        }
      }
    });
  }

  return params;
}
// 根据元素类型获取值
function getElementValue(element) {
  if (!element) return "";

  switch (element.tagName.toLowerCase()) {
    case "input":
      switch (element.type.toLowerCase()) {
        case "checkbox":
          return element.checked;
        case "radio":
          const checkedRadio = document.querySelector(
            `input[name="${element.name}"]:checked`
          );
          return checkedRadio ? checkedRadio.value : "";
        default:
          return element.value;
      }
    case "select":
      return element.value;
    case "textarea":
      return element.value;
    default:
      return element.innerText;
  }
}

/**
 * 获取前端性能监控数据
 */
export function getPerformanceInfo() {
  if (performance) {
    const domContentLoaded =
      performance.timing.domContentLoadedEventStart -
      performance.timing.navigationStart;
    const load =
      performance.timing.loadEventStart - performance.timing.navigationStart;

    return {
      dom_content_load: domContentLoaded,
      resource_load: load,
      page_load: load,
    };
  }
}

export function getQuery() {
  const result = {};
  const parts = window.location.search.substr(1).split("&");
  for (let i = 0; i < parts.length; i++) {
    const pair = parts[i].split("=");
    if (pair[0] && pair[1]) {
      result[pair[0]] = decodeURIComponent(pair[1]);
    }
  }
  return result;
}
